package com.shuhe.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shuhe.domain.api.ApiRequestBody;
import com.shuhe.domain.api.ApiResponseBody;
import com.shuhe.metastore.DBSql;
import com.shuhe.metastore.MetaMysql;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Array;
import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;

import static com.shuhe.common.CommonFunction.*;


public class DataOperateHandler extends HttpServlet {

    private static Logger logger = Logger.getLogger(DataOperateHandler.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {


            resp = setResponse(resp);
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("application/json");
            String tokenKey = req.getHeader("token");
            if (tokenKey == null) {
                return;
            }

            String resultStr = "";

            resp.getWriter().write(resultStr);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void makeFailBody(String msg, HttpServletResponse resp, Connection metaConn, String id) throws Exception {
        ApiResponseBody body = new ApiResponseBody();
        body.setStatus("201");
        body.setMsg(msg);
        SimpleDateFormat nyr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String res_time = nyr.format(new Date());
        String sql = "update data_api_log set res_time='" + res_time
                + "',res_status='fail',err_detail='失败：" + msg + "' where id='" + id + "'";
        MetaMysql.execSql(metaConn, sql);
        resp.getWriter().write(JSONObject.toJSONString(body));
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection dbConn = null;
        Connection metaConn = null;
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        try {
            metaConn = MetaMysql.connect();
            dbConn = DBSql.connect();
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("application/json");
            resp = setResponse(resp);
            String bodyStr = readAsChars(req);
            JSONObject bodyJson = JSONObject.parseObject(bodyStr);
            SimpleDateFormat nyr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String req_time = nyr.format(new Date());

            String tokenKey = req.getParameter("token");
            if (tokenKey == null) {
                tokenKey = "";
            }

            String tableName = bodyJson.getString("tableName");
            if (tableName == null) {
                tableName = "";
            }

            String operateType = bodyJson.getString("operateType");
            if (operateType == null) {
                operateType = "";
            }

            if (!tokenKey.equals("dsjpt")) {
                makeFailBody("用户没有权限", resp, metaConn, id);
                return;
            }
            if (tableName.length() == 0) {
                makeFailBody("表名为必传参数", resp, metaConn, id);
                return;
            }

            String db_name = "";
            String sql = "select db_name, column_name from mxgc_user_column where table_name = '" + tableName + "'";
            ResultSet rs = MetaMysql.querySql(metaConn, sql);
            ArrayList columns = new ArrayList();
            while (rs.next()) {
                db_name = rs.getString("db_name");
                columns.add(rs.getString("column_name"));
            }

            if (db_name.length() == 0) {
                makeFailBody("访问表不存在", resp, metaConn, id);
                return;
            }


            //请求日志
            sql = "insert into data_api_log(\n" +
                    "id,user_name,req_time,table_ename,table_columns,order_column,off_set,off_rows)\n" +
                    "values('" + id + "','" +
                    tokenKey + "','" + req_time + "','" + tableName + "','" + operateType + "','" + "" + "','"
                    + "" + "','" + "" + "')";
            MetaMysql.execSql(metaConn, sql);


            sql = " insert into " + db_name + "." + tableName;
            JSONArray datas = bodyJson.getJSONArray("datas");
            int records = 0;
            if (datas != null) {
                for (int i = 0; i < datas.size(); i++) {
                    JSONObject data = datas.getJSONObject(i);
                    String fieldValue = "";
                    String fieldName = "";
                    for (int j = 0; j < columns.size(); j++) {
                        String column = (String) columns.get(j);
                        fieldValue = fieldValue + "'" + data.getString(column) + "',";
                        fieldName = fieldName + column + ",";

                    }
                    String sql1 = sql + "(" + fieldName.substring(0, fieldName.length() - 1) + ") values("
                            + fieldValue.substring(0, fieldValue.length() - 1) + ")";
                    records = records + 1;

                    if (i == 0) {
                        DBSql.execSql(dbConn, "delete from " + db_name + "." + tableName);
                    }
                    DBSql.execSql(dbConn, sql1);
                }
            }

            ApiResponseBody body = new ApiResponseBody();
            body.setStatus("200");
            body.setMsg("查询成功");
            body.setTotalRowNumber(String.valueOf(records));
            String res_body = JSONObject.toJSONString(body);
            int resLen = res_body.length();
            if (resLen > 499) {
                resLen = 499;
            }
            sql = "update data_api_log set res_time='" + nyr.format(new Date()) + "',res_body='"
                    + res_body.substring(0, resLen) + "',res_status='success' where id='" + id + "'";
            MetaMysql.execSql(metaConn, sql);
            String resultStr = JSONObject.toJSONString(res_body).replaceAll("\\\\", "");
            resp.getWriter().write(resultStr);

        } catch (Exception ex) {
            try {
                int exLen = ex.getMessage().length();
                if (exLen > 499) {
                    exLen = 499;
                }
                makeFailBody(ex.getMessage().substring(0, exLen), resp, metaConn, id);
            } catch (Exception ex1) {

            }
            ex.printStackTrace();
        } finally {
            closeDb(dbConn);
            closeDb(metaConn);
        }
    }


    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp = setResponse(resp);
    }
}
